/* eslint-disable no-param-reassign */
import { useStore } from '@/hooks';
import { Button, Dialog, Form, Upload } from '@alifd/next';
import React, { useEffect, useRef, useState } from 'react';
import { t } from '@lingui/macro';
import DrawerFooter from '@/components/DrawerFooter';
import { FieldsGrid, TitleGrid } from '../stores/definitions';
import { observer } from 'mobx-react-lite';
import { observable } from 'mobx';
import moment from 'moment';

const FromItem = Form.Item;

const DataForm = ({ modal, companyId, onCancel, onSubmit, handleCustomRequest }) => {
  const { companyStore: store } = useStore();
  // 使用useRef进行拼接字段且不会造成重绘
  const editCtx = useRef({ origin: {}, changed: {} }).current; // 用于计算是否修改
  const [isViewMode] = useState(modal?.show === 'view');
  const formProps = isViewMode ? { field: false } : {};
  const [company] = useState(() => observable({}));
  const [disabledAdd, setDisabledAdd] = useState(false);
  const uploaderRef = useRef();
  useEffect(() => { if (modal?.toClose?.startsWith?.('toClose')) handleCancel(); }, [modal]);

  useEffect(() => {
    if (companyId) {
      (async () => {
        const data = await store.get(companyId);
        if (data?.logo && JSON.stringify(data.logo) !== '[]') {
          setDisabledAdd(true);
        }
        editCtx.origin = _.cloneDeep(data);
        _.assign(company, { ...data });
      })();
    } else {
      // 添加时给初始值
      _.set(company, 'singleDriver', false);
    }
  }, []);

  if (!company) return <></>;

  const overrideModel = {
    logo: {
      label: t`公司LOGO`,
      ui: {
        renderer: (r) => {
          const img = r?.map((item) => {
            if (item.originFileObj) {
              return item;
            }
            return ({
              uid: item.uid,
              state: 'done',
              name: item.title,
              type: item.type,
              url: `${API_BASE}/api/files/${item.uid}`,
              downloadURL: `${API_BASE}/api/files/${item.uid}`,
              imgURL: `${API_BASE}/api/files/${item.uid}?${moment()}`,
            });
          });
          return (
            <Upload.Card
              listType="card"
              value={img}
              name="logo"
              beforeUpload={beforeUpload}
              headers={{ Authorization: `Bearer ${TOKEN}` }}
              data={(file) => {
                return { binaryId: file.uid, mimeType: file.type };
              }}
              autoUpload={false}
              ref={saveUploaderRef}
              onPreview={handlePreview}
              formatter={(res, files) => {
                return {
                  uid: files.uid,
                  name: files.name,
                  state: 'done',
                  type: files.type,
                  url: `${API_BASE}/api/files/${files.uid}`,
                  downloadURL: `${API_BASE}/api/files/${files.uid}`,
                  imgURL: `${API_BASE}/api/files/${files.uid}`,
                };
              }}
              request={customRequest}
              onChange={handleUploadAdd}
              useDataURL
              action={`${API_BASE}/upload`}
              accept="image/png, image/jpg, image/jpeg, image/gif, image/bmp, image/webp"
            />
          );
        },
      },
    },
  };

  /**
   * @description 动态回现表单数据
   * @param {*} values
   * @param {*} item 数据Items
   */
  const handleChange = (values, item) => {
    const { name, value } = item;
    _.set(company, name, value);
    // 联动效果可以在这里通过设置channel属性实现
    if (name === 'independentAccount.collectionAccountInformation.type') {
      _.unset(company, 'independentAccount.collectionAccountInformation.name');
      _.unset(company, 'independentAccount.collectionAccountInformation.accountIdentification');
    }
    // eslint-disable-next-line eqeqeq
    editCtx.changed[name] = value == _.get(editCtx.origin, name) ? undefined : value;
  };


  const saveUploaderRef = (ref) => {
    if (ref) uploaderRef.current = ref.getInstance();
  };

  const beforeUpload = (info, options) => {
    return options;
  };

  const customRequest = (data) => {
    handleCustomRequest(data);
  };

  /**
  * @description 上传组件事件
  * @param {*} v
  */
  const handleUploadAdd = (v) => {
    if (v?.length >= 1) {
      _.set(company, 'logo', v);
      setDisabledAdd(true);
    } else {
      setDisabledAdd(false);
    }
  };

  const handlePreview = ({ url }) => {
    Dialog.show({
      title: t`预览`,
      content: <img src={url} style={{ maxWidth: '800px', width: '100%', height: '100%', objectFit: 'cover' }} />,
      footer: false,
    });
  };

  /**
   * @description 提交表单实现修改车辆
   * @param {*} r formData
   */
  const handleSubmit = (values, errors) => {
    if (!_.isEmpty(errors)) {
      console.log('🚀 _ file: DataForm.jsx:162 _ errors:', errors);
      return;
    }
    const { dateOfIncorporate, logo = [] } = company;
    const data = {
      ...company,
      dateOfIncorporate: moment.utc(dateOfIncorporate).toISOString(),
    };
    let toggleImg = [];
    if (JSON.stringify(logo) !== '[]') {
      toggleImg = logo?.map((item) => ({
        title: item.name,
        uid: company?.id,
        type: item.type,
      }));
    }
    onSubmit?.({ ...data, logo: toggleImg });
    uploaderRef.current && uploaderRef.current.startUpload();
  };
  const handleCancel = () => {
    // eslint-disable-next-line no-return-assign
    if (!_.isEmpty(_.transform(editCtx.changed, (r, v, k) => v !== undefined && (r[k] = v)))) {
      Dialog.confirm({
        content: t`放弃修改内容？`,
        onOk: () => onCancel?.(),
      });
      return;
    }
    onCancel?.();
  };

  return (
    <Form
      inline
      isPreview={isViewMode}
      {...formProps}
      value={company}
      onChange={handleChange}
      useLabelForErrorMessage
    >
      <TitleGrid title={t`公司信息`} />
      <FieldsGrid
        formData={company}
        mode={isViewMode}
        overrideModel={overrideModel}
        fields={['id']}
      />

      <DrawerFooter>
        <FromItem>
          {!isViewMode && <Form.Submit validate type="primary" onClick={handleSubmit}>{t`保存`}</Form.Submit>}
          <Button style={{ marginLeft: 8 }} onClick={handleCancel}>{t`取消`}</Button>
        </FromItem>
      </DrawerFooter>

    </Form>
  );
};

export default observer(DataForm);
